package org.papervision3d.core.animation.track
{
	import org.papervision3d.core.animation.keyframe.AbstractKeyFrame;
	import org.papervision3d.core.geom.renderables.Vertex3D;
	import org.papervision3d.core.log.PaperLogger;
	import org.papervision3d.objects.DisplayObject3D;

	public class MorphTrack extends AbstractTrack
	{
		public function MorphTrack(target:DisplayObject3D)
		{
			super(target);
		}
		
		public override function addKeyFrame(keyframe:AbstractKeyFrame):void
		{
			if(!keyframe.data || !target.geometry || !target.geometry.vertices || keyframe.data.length != target.geometry.vertices.length)
			{
				PaperLogger.error("Invalid keyframe data: should be an array matching the length of the geometry.vertices array!");
				return;
			}
			super.addKeyFrame(keyframe);
		}
		
		public override function tick(seconds:Number):void
		{	
			if(!target || !target.geometry || !target.geometry.vertices)
			{
				return;
			}
			
			super.tick(seconds);
			
			var vertices :Array = target.geometry.vertices;
			var i :int = vertices.length;
			var vertex :Vertex3D;
			var u :Vertex3D;
			var v :Vertex3D;
			
			if(current && next)
			{
				while(vertex = vertices[--i])
				{
					u = current.data[i];
					v = next.data[i];
					vertex.x = u.x + alpha * (v.x - u.x);
					vertex.y = u.y + alpha * (v.y - u.y);
					vertex.z = u.z + alpha * (v.z - u.z);
				}	
			}
			else if(current)
			{
				while(vertex = vertices[--i])
				{
					u = current.data[i];
					vertex.x = u.x;
					vertex.y = u.y;
					vertex.z = u.z;
				}	
			}
		}
	}
}